import {reactive} from 'vue'
import http from '@/utils/axios.js'
const url = 'app/pan/index/upload'
class FileQueue {
  constructor(maxUploadingCount = 3, handle = function (item) {
    setTimeout(() => console.log('Upload success:', item.name), Math.random() * 2000)
  }) {
    this.queue =reactive([]) //等待队列
    this.completion=reactive([]) //完成
    this.uploadingCount = 0
    this.maxUploadingCount = maxUploadingCount
    this.handle = handle
  }
  addFile(item) {
    this.queue.push(item)
    this.uploadFiles()
  }
  clearCompletion(){
    this.completion
  }
  async uploadFiles() {
    while (this.uploadingCount < this.maxUploadingCount && this.queue.length > 0) {
      const item = this.queue.shift()
      const uploadPromise = this.uploadFile(item)
        .then(() => {
          this.uploadingCount--
        })
        .catch((err) => {
          console.error('Failed to upload file:', err)
          this.uploadingCount--
        }).finally(()=>{
          item.isUpload=true
          const i=this.completion.findIndex(t=>t===item)
          this.completion.splice(i)
        })
      this.uploadingCount++
      await uploadPromise
    }
  }
  async uploadFile(item) {
    // 这里写具体的上传逻辑，可以使用fetch、XMLHttpRequest等方法
    
    this.completion.push(item)
    
    const handle = this.handle
    await handle(item)
  }
}
export default FileQueue
//item:{formData:new FormData(),fileName,isUpload:false,progress:0,success:()=>{},fail:()=>{},complete:()=>{},onUploadProgress:()=>{}}
export const fileQueueHandle = new FileQueue(3, (item = {}) => {
  return http.post('app/pan/index/upload', item.formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress:item.onUploadProgress
  }).then(res => {
    item.success && item.success(res)//typeof item.success === 'function' && 
  }).catch(err => {
    item.fail && item.fail(res)//typeof item.fail === 'function' && 
  }).finally(() => {
    item.complete && item.complete()//typeof item.complete === 'function' && 
  })
})

/* // 示例代码
const fileQueue = new FileQueue()
const files = [{
 name: 'file1'
},
{
 name: 'file2'
},
{
 name: 'file3'
},
{
 name: 'file4'
},
{
 name: 'file5'
},
{
 name: 'file6'
},
{
 name: 'file7'
},
{
 name: 'file8',
 success (res){
   console.log(res)
 }
},
{
 name: 'file9'
},
{
 name: 'file10'
},
]
files.forEach(async (file,index) => {
setTimeout(() => {
 fileQueue.addFile(file)
}, Math.random() * 5000)

}) */